const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');

const router = express.Router();

// 验证JWT中间件
const authMiddleware = async (req, res, next) => {
  try {
    // 从header中获取token
    const token = req.header('Authorization')?.replace('Bearer ', '');
    if (!token) {
      return res.status(401).json({ message: '未授权，请先登录' });
    }

    // 验证token
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
    
    // 查找用户
    const user = await User.findById(decoded.userId);
    if (!user) {
      return res.status(401).json({ message: '用户不存在' });
    }

    // 将用户信息添加到请求对象
    req.user = user;
    req.userId = user._id;
    
    next();
  } catch (error) {
    console.error('授权错误:', error);
    res.status(401).json({ message: '授权无效，请重新登录' });
  }
};

// 注册路由
router.post('/register', async (req, res) => {
  try {
    const { username, email, password } = req.body;

    // 检查用户是否已存在
    const existingUser = await User.findOne({ $or: [{ email }, { username }] });
    if (existingUser) {
      return res.status(400).json({ message: '用户名或邮箱已被注册' });
    }

    // 加密密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建新用户
    const user = new User({
      username,
      email,
      password: hashedPassword,
      carbonFootprint: 50,  // 设置初始碳足迹
      greenEnergy: 10,      // 设置初始绿色能量
      planetState: {
        pollution: 30,      // 初始污染度
        biodiversity: 70,   // 初始生物多样性
        energy: {
          clean: 30,        // 初始清洁能源
          total: 100        // 初始总能源
        },
        buildings: [],      // 初始建筑
        trees: 100,         // 初始树木数量
        waterQuality: 80    // 初始水质
      },
      achievements: [],     // 初始成就为空
      tasks: []            // 初始任务为空
    });

    await user.save();

    // 生成 JWT token
    const token = jwt.sign(
      { userId: user._id },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '7d' }
    );

    // 返回用户信息（不包含密码）
    const userResponse = {
      id: user._id,
      username: user.username,
      email: user.email,
      carbonFootprint: user.carbonFootprint,
      greenEnergy: user.greenEnergy,
      planetState: user.planetState,
      achievements: user.achievements,
      tasks: user.tasks
    };

    res.status(201).json({
      token,
      user: userResponse
    });
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '服务器错误，请稍后重试' });
  }
});

// 登录路由
router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;

    // 查找用户
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(400).json({ message: '用户不存在' });
    }

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
      return res.status(400).json({ message: '密码错误' });
    }

    // 生成 JWT token
    const token = jwt.sign(
      { userId: user._id },
      process.env.JWT_SECRET || 'your-secret-key',
      { expiresIn: '7d' }
    );

    // 返回用户信息（不包含密码）
    const userResponse = {
      id: user._id,
      username: user.username,
      email: user.email,
      carbonFootprint: user.carbonFootprint,
      greenEnergy: user.greenEnergy,
      planetState: user.planetState,
      achievements: user.achievements,
      tasks: user.tasks
    };

    res.json({
      token,
      user: userResponse
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误，请稍后重试' });
  }
});

// 更新用户数据
router.put('/updateUser', authMiddleware, async (req, res) => {
  try {
    const { carbonFootprint, greenEnergy, planetState, tasks, achievements } = req.body;
    
    // 查找并更新用户
    const user = await User.findById(req.userId);
    
    // 更新用户数据
    if (carbonFootprint !== undefined) user.carbonFootprint = carbonFootprint;
    if (greenEnergy !== undefined) user.greenEnergy = greenEnergy;
    if (planetState) user.planetState = planetState;
    if (tasks) user.tasks = tasks;
    if (achievements) user.achievements = achievements;
    
    // 保存更新
    await user.save();
    
    // 返回更新后的用户数据
    const userResponse = {
      id: user._id,
      username: user.username,
      email: user.email,
      carbonFootprint: user.carbonFootprint,
      greenEnergy: user.greenEnergy,
      planetState: user.planetState,
      achievements: user.achievements,
      tasks: user.tasks
    };
    
    res.json({
      user: userResponse,
      message: '用户数据更新成功'
    });
  } catch (error) {
    console.error('更新用户数据错误:', error);
    res.status(500).json({ message: '服务器错误，请稍后重试' });
  }
});

module.exports = router; 